package com.algrithom.tree.binarytree;

import java.util.Objects;

import com.common.model.TreeNode;
import com.util.TreeOperUtil;

/**
 * 129. 求根节点到叶节点数字之和
 */
public class Solution5 {
    
    public static void main(String[] args) {
        Integer[] nums = new Integer[]{4,9,0,5,1};
        Solution5 solution5 = new Solution5();
        TreeNode<Integer> root = TreeOperUtil.createTree(nums,0);
        System.out.println(solution5.sumNumbers(root));
    }
    
    public int sumNumbers(TreeNode<Integer> root){
        if (Objects.isNull(root)) {
            return 0;
        }
        return dfs(root,"");
    }
    
    private int dfs(TreeNode<Integer> root,String str){
        if (Objects.isNull(root)) {
            return Integer.parseInt(str);
        }
        str = str + root.getValue();
        if (Objects.nonNull(root.getLeftChild()) && Objects.nonNull(root.getRightChild())) {
            return dfs(root.getLeftChild(),str) + dfs(root.getRightChild(),str);
        } else if (Objects.nonNull(root.getLeftChild())) {
            return dfs(root.getLeftChild(),str);
        } else {
            return dfs(root.getRightChild(),str);
        }
    }
}
